package com.alex.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class MultiThreadSum {
    public static void main(String[] args) {
        // 使用原子长整型来保证线程安全
        AtomicLong totalSum = new AtomicLong(0);

        // 创建线程池，固定10个线程
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 每个线程处理10个数字 (100/10 = 10)
        int numbersPerThread = 10;

        // 提交10个任务
        for (int i = 0; i < 10; i++) {
            final int start = i * numbersPerThread + 1;
            final int end = (i == 9) ? 100 : (i + 1) * numbersPerThread;

            executor.submit(() -> {
                long threadSum = 0;
                for (int j = start; j <= end; j++) {
                    threadSum += j;
                }

                // 原子性地添加到总和中
                long currentTotal = totalSum.addAndGet(threadSum);
                System.out.println(Thread.currentThread().getName() +
                        " 计算 " + start + "-" + end + " 的和: " + threadSum +
                        "，当前总和: " + currentTotal);
            });
        }

        // 关闭线程池
        executor.shutdown();

        // 等待所有任务完成
        while (!executor.isTerminated()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        System.out.println("\n最终结果: 1-100的总和 = " + totalSum.get());
        System.out.println("理论值: 1-100的总和 = " + (100 * 101 / 2));
    }
}
